import React, { Component } from 'react'
import { View, Text, StyleSheet, TextInput, AsyncStorage } from 'react-native'

const KEY = 'save_key'
export default class AsyncStorageDemoPage extends Component {
	constructor(props) {
		super(props)
		this.state = {
			showText: ''
		}
	}

	doSave() {
		AsyncStorage.setItem(KEY, this.value, error => {
			error && console.log(error.toString())
		})
	}

	doRemove() {
		AsyncStorage.removeItem(KEY, error => {
			error && console.log(error.toString())
		})
	}

	getData() {
		AsyncStorage.getItem(KEY, (error, value) => {
			this.setState({
				showText: value
			})
		})
	}

	render() {
		return (
			<View style={styles.container}>
				<Text style={styles.welcome}>AsyncStorage 使用</Text>
				<TextInput
					style={styles.input}
					onChangeText={text => {
						this.value = text
					}}
				/>
				<View style={styles.input_container}>
					<Text
						onPress={() => {
							this.doSave()
						}}
					>
						存储
					</Text>
					<Text
						onPress={() => {
							this.doRemove()
						}}
					>
						删除
					</Text>
					<Text
						onPress={() => {
							this.getData()
						}}
					>
						获取
					</Text>
				</View>
				<Text>{this.state.showText}</Text>
			</View>
		)
	}
}

const styles = StyleSheet.create({
	container: {
		flex: 1,
		backgroundColor: '#f5fcff'
	},
	welcome: {
		fontSize: 16,
		textAlign: 'center'
	},
	input_container: {
		flexDirection: 'row',
		alignItems: 'center',
		justifyContent: 'space-around',
		margin: 10
	},
	input: {
		height: 30,
		// flex: 1,
		borderColor: 'black',
		borderWidth: 1
	}
})
